<template>
  <view class="login-container">
    <!-- Logo区域 -->
    <view class="logo-section">
      <image class="logo" src="@/static/images/logo.png" mode="aspectFit" />
      <text class="platform-name">红木家具交易平台</text>
    </view>
    
    <!-- 登录表单 -->
    <view class="form-container">
      <uni-forms ref="form" :modelValue="formData" :rules="rules">
        <!-- 用户名输入 -->
        <uni-forms-item name="username">
          <uni-easyinput 
            v-model="formData.username"
            placeholder="请输入用户名"
            prefixIcon="person"
            :inputBorder="false"
          />
        </uni-forms-item>
        
        <!-- 密码输入 -->
        <uni-forms-item name="password">
          <uni-easyinput 
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            prefixIcon="locked"
            :inputBorder="false"
            @confirm="handleLogin"
          />
        </uni-forms-item>
        
        <!-- 登录按钮 -->
        <button 
          class="login-btn" 
          :loading="loading" 
          @click="handleLogin"
          :disabled="loading"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
        
        <!-- 注册链接 -->
        <view class="register-link">
          <text>没有账号？</text>
          <text class="link-text" @click="navToRegister">立即注册</text>
        </view>
      </uni-forms>
    </view>
    
    <!-- 底部版权信息 -->
    <view class="footer">
      <text>© 2023 金牌涛红木家具平台</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        username: '',
        password: ''
      },
      loading: false,
      rules: {
        username: {
          rules: [{
            required: true,
            errorMessage: '请输入用户名'
          }, {
            minLength: 3,
            errorMessage: '用户名至少3个字符'
          }]
        },
        password: {
          rules: [{
            required: true,
            errorMessage: '请输入密码'
          }, {
            minLength: 6,
            errorMessage: '密码长度不能少于6位'
          }]
        }
      }
    }
  },
  methods: {
    async handleLogin() {
      try {
        // 表单验证
        const valid = await this.$refs.form.validate();
        if (!valid) return;
        
        this.loading = true;
        
        // 调用登录云函数
        const res = await uniCloud.callFunction({
          name: 'user', // 确保云函数名称正确
          data: {
            action: 'login', // 指定登录操作
            params: {
              username: this.formData.username,
              password: this.formData.password
            }
          }
        });
        
        const result = res.result;
        
        if (result.code === 0) {
          // 登录成功处理
          this.saveLoginData(result);
          
          uni.showToast({
            title: '登录成功！欢迎回来',
            icon: 'success',
            duration: 1500
          });
          
          // 跳转到首页
          setTimeout(() => {
            // 根据用户角色跳转到不同页面
            if (result.userInfo.role === 'admin') {
              uni.switchTab({
                url: '/pages/home/index'
              });
            } else {
              uni.switchTab({
                url: '/pages/home/index'
              });
            }
          }, 1600);
        } else {
          // 登录失败
          throw new Error(result.message || '登录失败');
        }
      } catch (e) {
        console.error('登录失败:', e);
        uni.showToast({
          title: e.message || '登录失败，请检查用户名和密码',
          icon: 'none',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },
    
    saveLoginData(result) {
      // 保存用户信息到本地存储
      const userInfo = result.userInfo || {
        uid: result.uid,
        username: this.formData.username
      };
      
      uni.setStorageSync('userInfo', userInfo);
      
      // 设置登录状态
      uni.setStorageSync('isLogin', true);
      
      // 触发全局登录状态更新
      uni.$emit('loginStatusChanged', true);
    },
    
    navToRegister() {
      uni.navigateTo({
        url: '/pages/users/register'
      });
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  min-height: 100vh;
  padding: 60rpx 40rpx;
  background-color: #f8f3ed;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 80rpx;
}

.logo {
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  background-color: white;
  padding: 10rpx;
  box-shadow: 0 4rpx 20rpx rgba(92, 60, 28, 0.2);
  border: 2rpx solid #e8c39e;
}

.platform-name {
  font-size: 36rpx;
  color: #5c3c1c;
  font-weight: bold;
  margin-top: 30rpx;
  letter-spacing: 2rpx;
}

.form-container {
  width: 100%;
  max-width: 600rpx;
  margin-top: 80rpx;
}

.login-btn {
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  margin-top: 60rpx;
  background-color: #5c3c1c;
  color: white;
  font-size: 32rpx;
}

.register-link {
  display: flex;
  justify-content: center;
  margin-top: 40rpx;
  font-size: 28rpx;
  color: #5c3c1c;
}

.link-text {
  color: #d42828;
  margin-left: 10rpx;
  text-decoration: underline;
}

.footer {
  margin-top: auto;
  padding: 30rpx 0;
  font-size: 24rpx;
  color: #999;
}
</style>